package com.yssoft.controller.app.system;

import com.yssoft.entity.core.*;
import com.yssoft.service.core.*;
import com.yssoft.utils.AppUtil;
import com.yssoft.utils.ObjectConversion;
import com.yssoft.utils.verificationCode.CCPRestSDK;

import org.apache.log4j.Logger;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author 陈翼东
 * @说明 app中登录
 * @time 2018/4/28 下午 04:20
 */
@CrossOrigin//解决跨域session问题
@Controller("AppLoginController")
@RequestMapping("/app")
public class AppLoginController {
    
    private static Logger logger = Logger.getLogger(AppLoginController.class);
    
    @Resource
    private AccountsService accountsService;
    @Resource
    private PersonService personService;
    @Resource
    private EnterpriseService enterpriseService;
    @Resource
    private DepartmentService departmentService;
    
    @Resource
    private AppUpdateService appUpdateService;
    
    /**
     * 登录提交方法(更多信息待封装),登录之后将用户信息存储到session中
     * @param loginName  登录账号或者手机号
     * @param password  登录密码
     * @return
     */
    @RequestMapping(name = "/login", value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object loginSuccess(String loginName, String password, HttpServletRequest request) {
        TAccounts accounts = accountsService.queryAccByLoginName(loginName);
        TPersonnel personnel = null;
        if (accounts == null) {
            //手机号登录
            String telRegex = "[1][123456789]\\d{9}";
            if (loginName != null && loginName.matches(telRegex)) {
                //当前是手机号
                personnel = personService.queryPersonByPhone(loginName);//如果使用手机号登录，则使用手机号查询人员
            } else {
                return AppUtil.returnMapJson("0", "请验证您的账号!", null);
            }
            if (personnel == null) {
                return AppUtil.returnMapJson("0", "手机号或帐号不存在!", null);
            } else {
                accounts = accountsService.queryAccountByPersonId(personnel.getId());
                if (accounts != null) {
                    //用户传输过来的密码
                  
                    String newSashPassword = new SimpleHash("MD5", password == null ? "" : password, accounts.getSalt(), 2).toString();
                    //数据库中查询的密码
                    String sashPassword = accounts.getPassword();
                    if (newSashPassword.equals(sashPassword)) {
                        Map<String, Object> user = new HashMap<>();//用户信息
                        try {
                            Map<String, Object> userMap = ObjectConversion.getObjectToMap(personnel);//将实体转换成map
                            if (personnel != null) {
                            	userMap.put("loginName", loginName);
                            	userMap.put("accId", accounts.getId());
                            	userMap.put("entId",  personnel.gettEId());
                                Integer entId = personnel.gettEId();//企业id
                                TEnterprise ent = enterpriseService.queryEnterpriseById(entId);
                                if(ent!=null) {
                                    String eName = ent.getName();
                                    userMap.put("eName", eName);
                                }
                                List<String> roles = accountsService.queryRolesByAccId(accounts.getId());
                                userMap.put("roles", roles);
                                Map<String, Object> sessionMap = new HashMap<String, Object>();
                                sessionMap.putAll(userMap);
                                TDepartment dept = departmentService.queryTDepartmentById(personnel.gettDId());
                                if(dept!=null) {
                                    userMap.put("dName", dept.getName());
                                }
                                Set<String> functions = this.accountsService.queryPermissionForList(accounts.getId());
                                userMap.put("functions",functions);
                                
                                user.put("user", userMap);
                                sessionMap.put("companyName", ent == null ? "" : ent.getName());
                                sessionMap.put("deptName", dept == null ? "" : dept.getName());
                                HttpSession session = request.getSession();
                                session.setAttribute("appUser", sessionMap);
                                return AppUtil.returnMapJson("1", "登录成功!", user);
                            } else {
                                return AppUtil.returnMapJson("0", "账号没有关联人员信息!", null);
                            }
            
                        } catch (IllegalAccessException e) {
                            logger.info("实体转换失败:" + e.getMessage());
                            return AppUtil.returnMapJson("0", "登录失败,请重试!", null);
                        }
                    } else {
                        return AppUtil.returnMapJson("0", "登录密码错误!", null);
                    }
                }else{
                    return AppUtil.returnMapJson("0", "该人员没有开通账号!", null);
                }
            }
        } else {
            //账号密码登录
            String newSashPassword = new SimpleHash("MD5", password == null ? "" : password, accounts.getSalt(), 2).toString();
            //数据库中查询的密码
            String sashPassword = accounts.getPassword();
            if (newSashPassword.equals(sashPassword)) {
                //获取账户对应的人员
                Integer persionId = accounts.gettPId();
                Map<String, Object> user = new HashMap<>();//用户信息
                if (persionId != null) {
                    personnel = personService.queryPersonById(persionId + "");
                    try {
                        Map<String, Object> userMap = ObjectConversion.getObjectToMap(personnel);//将实体转换成map
                        Integer entId = personnel.gettEId();//企业id
                        TEnterprise ent = enterpriseService.queryEnterpriseById(entId);
                        userMap.put("entId",  personnel.gettEId());
                        if(ent!=null) {
                            String eName = ent.getName();
                            userMap.put("eName", eName);
                        }
                        userMap.put("loginName", loginName);
                        userMap.put("accId", accounts.getId());
                        List<String> roles = accountsService.queryRolesByAccId(accounts.getId());
                        userMap.put("roles", roles);
                        TDepartment dept = departmentService.queryTDepartmentById(personnel.gettDId());
                        if(dept!=null) {
                            userMap.put("dName", dept.getName());
                        }
                        Set<String> functions = this.accountsService.queryPermissionForList(accounts.getId());
                        userMap.put("functions",functions);
                        user.put("user", userMap);
                        Map<String, Object> sessionMap = new HashMap<String, Object>();
                        sessionMap.putAll(userMap);
                        sessionMap.put("companyName",ent==null?"":ent.getName());
                        sessionMap.put("deptName",dept==null?"":dept.getName());
                        HttpSession session = request.getSession();
                        session.setAttribute("appUser", sessionMap);
                        return AppUtil.returnMapJson("1", "登录成功!", user);
                    } catch (IllegalAccessException e) {
                        return AppUtil.returnMapJson("0", "登录失败,请重试!", null);
                    }
                }else{
                    return AppUtil.returnMapJson("0", "账号没有关联人员信息!", null);
                }
            } else {
                return AppUtil.returnMapJson("0", "登录密码错误!", null);
            }
        }
    }
    
    
    /**
     * 找回密码的时候获取验证码的接口
     * @param phoneNumber 获取验证码的手机号
     * @return
     */
    @RequestMapping(name = "getVerificationCode",value =  "getVerificationCode", method = RequestMethod.POST)
    @ResponseBody
    public Object getVerificationCode(String phoneNumber) {
        //String flag = "9";
        Map<String, Object> flag = new HashMap<>();
        flag.put("flag","9");
        // 传入参数电话号码不可空
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            HashMap<String, Object> result = null;
            CCPRestSDK restAPI = new CCPRestSDK();
            restAPI.init("app.cloopen.com", "8883");// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
            restAPI.setAccount("8a48b55150ac70fd0150acc34f1f01e4", "22ed8d4fa75e45978d35bc245326886d");// 初始化主帐号和主帐号TOKEN
            restAPI.setAppId("8aaf07085995ddef01599b9407660171");// 初始化应用ID
            
            int num = (int) ((Math.random() * 9 + 1) * 100000);
            // 这里生成验证码与验证码时限时间并存储表
            
            // sendTemplateSMS
            // 参数1:必选参数 短信接收端手机号码集合，用英文逗号分开，每批发送的手机号数量不得超过100个
            // 参数2:必选参数 模板Id
            // 参数3:可选参数 内容数据，用于替换模板中{序号}
            result = restAPI.sendTemplateSMS(phoneNumber, "153391", new String[]{num + "", "1"});
            System.out.println("SDKTestSendTemplateSMS result=" + result);
            if ("000000".equals(result.get("statusCode"))) {
                // 正常返回输出data包体信息（map）
                HashMap<String, Object> data = (HashMap<String, Object>) result.get("data");
                Set<String> keySet = data.keySet();
                for (String key : keySet) {
                    Object object = data.get(key);
                }
                flag.put("flag",num + "");
                return AppUtil.returnMapJson("1", "获取验证码成功!", flag);
            } else {
                // 异常返回输出错误码和错误信息
                flag.put("flag","9");
                return AppUtil.returnMapJson("0", "获取验证码失败!错误信息:" + result.get("statusMsg"), flag);
            }
        } else {
            flag.put("flag","9");
            return AppUtil.returnMapJson("0", "手机号不能为空!", flag);
        }
    }
    
    /**
     * 重置密码(通过手机号找回密码)
     * @param phoneNumber 设置的手机号
     * @param password 新的密码
     * @return
     */
    @RequestMapping(name = "resetPassword",value =  "resetPassword", method = RequestMethod.POST)
    @ResponseBody
    public Object resetPassword(String phoneNumber, String password) {
        try {
            TPersonnel person = personService.queryPersonByPhone(phoneNumber);
            TAccounts account = accountsService.queryAccountByPersonId(person.getId());
            String salt = System.currentTimeMillis() + account.gettPId() + "";
            account.setSalt(salt);//随机加密盐
            String newPassword = new SimpleHash("MD5", password, account.getSalt(), 2).toString();
            account.setPassword(newPassword);
            accountsService.updateAccountById(account);
            return AppUtil.returnMapJson("1", "修改密码成功!", null);
        } catch (Exception e) {
            logger.info("重置密码错误:" + e.getMessage());
            return AppUtil.returnMapJson("0", "修改密码失败!", null);
        }
    }
    
    /**
     * 验证用户是否对登录写的空方法
     * @return
     */
    @RequestMapping(value =  "isLogin", method = RequestMethod.POST)
    @ResponseBody
    public Object isLogin() {
        return AppUtil.returnMapJson("1", "已经登录!", null);
    }
    
    /**
     * app检查更新
     * @param request
     * @return
     */
    @RequestMapping("checkUploadVersion")
    @ResponseBody
    public Object checkUploadVersion(HttpServletRequest request){
        HashMap<String, Object> param = new HashMap<>();
        TAppUpdate update = appUpdateService.selectOne();
        param.put("uploadUrl",update.getUploadUrl());
        param.put("isWholePackage",update.getIsWholePackage());//是否整包更新0是,1不是
        param.put("uploadVersion",update.getUploadVersion());
        param.put("iphoneUploadUrl",update.getIphoneUploadUrl());
        return  AppUtil.returnMapJson("0","获取成功",param);
    }
}
